import { Controller, Get, Post, Body, Patch, Param, Delete, Query, UseGuards, BadRequestException } from '@nestjs/common';
import { ScriptsService } from './scripts.service';
import { CreateScriptDto, UpdateScriptDto, QueryScriptDto, ExecuteScriptDto } from './dto/scripts.dto';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
import { PermissionGuard } from '../common/guards/permission.guard';
import { CurrentUser } from '../common/decorators/current-user.decorator';
import { RequirePermissions } from '../common/decorators/permission.decorator';

@Controller('scripts')
@UseGuards(JwtAuthGuard, PermissionGuard)
export class ScriptsController {
  constructor(private readonly scriptsService: ScriptsService) {}

  @Post()
  @RequirePermissions('scripts:create')
  create(@Body() createScriptDto: CreateScriptDto, @CurrentUser() user: any) {
    return this.scriptsService.create(createScriptDto, user?.id);
  }

  @Get()
  @RequirePermissions('scripts:list')
  findAll(@Query() query: QueryScriptDto) {
    return this.scriptsService.findAll(query);
  }

  @Get(':id')
  @RequirePermissions('scripts:view')
  findOne(@Param('id') id: string) {
    return this.scriptsService.findOne(+id);
  }

  @Patch(':id')
  @RequirePermissions('scripts:update')
  update(@Param('id') id: string, @Body() updateScriptDto: UpdateScriptDto, @CurrentUser() user: any) {
    return this.scriptsService.update(+id, updateScriptDto, user?.id);
  }

  @Delete(':id')
  @RequirePermissions('scripts:delete')
  remove(@Param('id') id: string) {
    return this.scriptsService.remove(+id);
  }

  @Post(':id/execute')
  @RequirePermissions('scripts:execute')
  execute(@Param('id') id: string, @Body() executeDto: ExecuteScriptDto, @CurrentUser() user: any) {
    return this.scriptsService.execute(+id, user?.id, executeDto.args, executeDto.parameters);
  }

  @Get(':id/executions')
  @RequirePermissions('scripts:executions')
  getExecutions(
    @Param('id') id: string,
    @Query('page') page?: number,
    @Query('pageSize') pageSize?: number,
  ) {
    return this.scriptsService.getExecutions(+id, page, pageSize);
  }

  @Get('executions/:id')
  @RequirePermissions('scripts:execution-detail')
  getExecution(@Param('id') id: string) {
    const numericId = +id;
    if (isNaN(numericId) || numericId <= 0) {
      throw new BadRequestException(`Invalid execution ID: ${id}`);
    }
    return this.scriptsService.getExecution(numericId);
  }

  @Get(':id/parameters')
  @RequirePermissions('scripts:view')
  extractParameters(@Param('id') id: string) {
    return this.scriptsService.extractScriptParameters(+id);
  }
}